package org.eden.rpc.core.server;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import io.netty.util.concurrent.Future;
import org.eden.rpc.common.entity.RpcRequest;
import org.eden.rpc.common.entity.RpcResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyServerHandler extends SimpleChannelInboundHandler<RpcRequest> {

    private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);

    private static final EventExecutorGroup eventExecutorGroup = new DefaultEventExecutorGroup(32);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequest req) throws Exception {
        logger.info("收到请求：" + req);

        eventExecutorGroup.submit(() -> {
            logger.info("执行请求：" + req);
            String interfaceName = req.getInterfaceName();
            ServiceRegister serviceRegister = ServiceRegisterHolder.getServiceRegister();
            Object service = serviceRegister.getService(interfaceName);
            Object result = serviceRegister.invoke(service, req); // 调用服务端方法，可能会有耗时的操作
            ctx.writeAndFlush(RpcResponse.success(result));
            // future.addListener(ChannelFutureListener.CLOSE); // 需要保持长连接，所以不关闭通道
        });

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error(cause.getMessage());
        ctx.close();
    }
}
